package com.mangatta.ec2.monitor;

import android.util.Log;
import com.amazonaws.auth.AWSCredentials;
import com.amazonaws.services.ec2.AmazonEC2Client;
import com.amazonaws.services.ec2.model.DescribeInstancesResult;
import com.amazonaws.services.ec2.model.Instance;
import com.amazonaws.services.ec2.model.Reservation;
import com.mangatta.cloud.AmazonCloudWatchFactory;
import com.mangatta.cloud.ec2.Ec2Instance;

import java.util.ArrayList;
import java.util.List;

public class InstanceListMonitor {
    private static final String TAG = InstanceListMonitor.class.getSimpleName();

    private static AmazonEC2Client amazonEC2Client = null;

    public InstanceListMonitor(AWSCredentials awsCredentials) {
        AmazonCloudWatchFactory cloudWatchFactory = new AmazonCloudWatchFactory(awsCredentials);
        if (amazonEC2Client == null) {
            synchronized (InstanceListMonitor.this) {
                if (amazonEC2Client == null) {
                    amazonEC2Client = cloudWatchFactory.getAmazonEC2Client();
                }
            }
        }
    }

    @SuppressWarnings("unchecked")
    public List<Ec2Instance> getInstancesDetail() {
        DescribeInstancesResult describeInstancesResult = amazonEC2Client.describeInstances();
        List<Reservation> reservations = describeInstancesResult.getReservations();

        List<Ec2Instance> ec2Instances = new ArrayList<Ec2Instance>();
        for (Reservation res : reservations) {
            List<Instance> instances = res.getInstances();
            for (Instance instance : instances) {
                ec2Instances.add(Ec2Instance.getEc2Instance(instance));
            }
        }
        Log.d(TAG, "Instance Details: " + ec2Instances);
        return ec2Instances;
    }
}
